package org.jinyan.db.utils;

import java.lang.reflect.Type;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class BeanMapConverUtils {

	/**
	 * 
	 * @param bean
	 * @return
	 */
	public static Map<String,Object> beanToMap(Object bean) {
		String json = beanToString(bean);
		Type type = new TypeToken<Map<String,Object>>() {
		}.getType();
		Map<String,Object> result = stringToClass(json, type);
		return result;
	}

	/**
	 * @param map
	 * @param type
	 * @return
	 */
	public static Object mapToBean(Object map, Type type) {
		String json = beanToString(map);
		Object obj = stringToClass(json, type);
		return obj;

	}

	/**
	 * 把对象转换为字符串
	 * 
	 * @param bean
	 * @return
	 */
	public static String beanToString(Object bean) {
		return new Gson().toJson(bean);
	}

	/**
	 * 
	 * @param json
	 * @param type
	 * @return
	 */
	public static <T> T stringToClass(String json, Type type) {
		T t = new Gson().fromJson(json, type);
		return t;
	}

}
